package com.sanchunhui.psc.presenter

import android.util.Log
import com.google.gson.Gson
import com.j256.ormlite.android.AndroidDatabaseConnection
import com.sanchuihui.presenter.view.LoginView
import com.sanchunhui.psc.data.protocol.ResponseInfo
import com.sanchunhui.psc.ext.excute
import com.sanchunhui.psc.rx.BaseSubscriber
import com.sanchunhui.psc.service.UserService
import com.sanchunhui.psc.ui.activity.LoginActivity
import org.jetbrains.anko.toast
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.lang.Exception
import java.sql.Savepoint
import javax.inject.Inject

/**
 * @Author zyx
 * @Date 2021/4/26-17:02
 * @Dscribe
 */
class LoginPresenter @Inject constructor() : BasePresenter<LoginView>() {

    @Inject
    lateinit var userService: UserService

    /*
        登录
     */
    fun login(mobile: String, pwd: String) {
        if (!checkNetWork()) {
            return
        }
        mView.showLoading()
        userService.login(mobile, pwd).excute(object : BaseSubscriber<ResponseInfo>(mView) {
            override fun onNext(t: ResponseInfo) {
                mView.onLoginResult(t)
            }
        }, lifecycleProvider)

    }

    /*
    // 使用手机号码登录的业务
    fun loginByPhone(username: String, password: String) {

//        val loginCall = pscService.login(username,password)
//        loginCall.enqueue(callback)

        val loginReq = LoginReq(username, password)

        //TODO:要异步访问
        val observable: Observable<ResponseInfo> = pscService.login(loginReq)
        observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (it.code == 0) {
                    val json = it.data
                    Log.e("token", it.token)
                    parserJson(json.toString(),it.token)
                } else if (it.code == -1) {
                    //根据具体接口文档表示含义，比如定义-1为空数据
                    Log.e("psc", "定义-1为空数据")
                }
            },{
                Log.e("rxjava",it.localizedMessage)
            },{
                Log.e("rxjava","onComplete!")
            })
    }


    // 解析数据
     fun parserJson(json: String, tokenInfo:String?) {
        var user = Gson().fromJson(json, UserInfo::class.java)
        user.token = tokenInfo
        if (user != null) {
            // 缓存到内存中
            BaseApplication.mUser = user
            var connection:AndroidDatabaseConnection? = null
            var startPoint:Savepoint? = null
            try {
                // 缓存到本地数据库中，SqliteOpenhelper,要使用SQL语句
                //第三方ORM框架(ormLite，greendao),直接提交javabean
                val pscOpenHelper = PSCOpenHelper(loginActivity)
                val userDao = pscOpenHelper.getDao(UserInfo::class.java)
                //保证如果已有此用户，就不需要创建了
//            userDao.create(user)
//            userDao.createOrUpdate(user)
//            Log.e("login","创建新用户或者更新老用户信息")
                connection =
                    AndroidDatabaseConnection(pscOpenHelper.writableDatabase, true)
                startPoint = connection.setSavePoint("start")
                connection.isAutoCommit = false // 取消自动提交
                //TODO:区分新用户和老用户，并且统计比率
                val userList: List<UserInfo> = userDao.queryForAll()
                var isOldUser: Boolean = false
                for (i in 0 until userList.size) {
                    val u = userList.get(i)
                    if (u.id == user.id) {
                        isOldUser = true
                    }
                }
                if (isOldUser) {
                    userDao.update(user)
                    Log.e("login", "老用户更新信息")
                } else {
                    userDao.create(user)
                    Log.e("login", "新用户登录")
                }
                connection.commit(startPoint) // 提交事务
                Log.e("login","事务正常")
            }catch (e:Exception) {
                Log.e("login","出现ormlite事务异常"+e.localizedMessage)
                loginActivity.onLoginFailed()
                if (connection != null) {
                    connection.rollback(startPoint)
                }
            }
            loginActivity.onLoginSuccess()
        } else {
            loginActivity.onLoginFailed()
        }
    }

     */

}